package com.project.lk.nurseapp.utils;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.lidong.photopicker.ImageCaptureManager;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseActivity;
import com.project.lk.nurseapp.base.BaseFragment;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * 功能介绍：添加相册工具类
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */

public class AddPhoto {

    private static final int TAKE_PICTURE = 0x000001;
    public static Uri photoUri;

    public static ImageCaptureManager captureManager;

    //获取图片地址
    public static String getRealPathFromURI(Uri contentUri, List list, AppCompatActivity activity) {
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }

    /**
     * @param path 照片路径
     * @return角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    //显示弹窗
    public static void showPopupWindow(View view, List list, AppCompatActivity activity, BaseFragment fragment,
                                       int photoNum) {

        // 一个自定义的布局，作为显示的内容
        final View contentView = LayoutInflater.from(activity).inflate(
                R.layout.photo_popwindow_layout, null);

        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        //设置弹窗的项目点击事件
        setPopupMenuItem(contentView, list, activity,fragment ,popupWindow,photoNum);
        popupWindow.setTouchable(true);
        // view添加OnTouchListener监听判断获取触屏位置如果在布局外面则销毁弹出框
        contentView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // getTop View自身的顶边到其父布局顶边的距离,因为是根目录所以为0
                int height = contentView.findViewById(R.id.popup_window_layout).getTop();
                // getY 点击事件距离控件顶边的举例
                int y = (int) event.getY();
                // 当抬起 并且 y>height时（也就是 只要不点击ListView范围内）,dismiss popupWindow
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y > height) {
                        popupWindow.dismiss();
                    }
                }
                return true;
            }
        });

        // 设置SelectPicPopupWindow弹出窗体的背景
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框

        // 设置好参数之后再show
        // popupWindow.showAsDropDown(view);
        popupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    //设置弹窗的项目点击事件
    private static void setPopupMenuItem(View view, final List list, final AppCompatActivity activity,
                                         final BaseFragment fragment, final PopupWindow popupWindow,
                                         final int photoNum) {
        Button photoBut = (Button) view.findViewById(R.id.send_buy_take_photo);
        Button ablumBut = (Button) view.findViewById(R.id.send_buy_open_ablum);
        Button cancelBut = (Button) view.findViewById(R.id.send_buy_cancel);
        //设置拍照片，打开相机

        photoBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //照相
                takePicture(activity,fragment);
                //取消弹窗
                popupWindow.dismiss();

            }
        });
        //设置获取本地相册
        ablumBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAlbum(activity,fragment ,list,photoNum);
                //取消弹窗
                popupWindow.dismiss();
            }
        });
        cancelBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //取消弹窗
                popupWindow.dismiss();
            }
        });
    }

    public static void openAlbum(AppCompatActivity activity, BaseFragment fragment, List list, int photoNum) {
        //打开本地相册
        PhotoPickerIntent intent = new PhotoPickerIntent(activity);

        intent.setSelectModel(SelectModel.MULTI);
        // intent.setShowCarema(true); // 是否显示拍照， 默认false
        intent.setMaxTotal(photoNum); // 最多选择照片数量，默认为4
        intent.setSelectedPaths((ArrayList<String>) list); // 已选中的照片地址， 用于回显选中状态
        fragment.startActivityForResult(intent, REQUEST_CAMERA_CODE);
    }



    //打开摄像头
    public static void takePicture(FragmentActivity activity, BaseFragment fragment) {
        try {
            if (captureManager == null) {
                captureManager = new ImageCaptureManager(activity);
            }
            Intent intent = captureManager.dispatchTakePictureIntent(activity);
            fragment.startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            Toast.makeText(activity, R.string.msg_no_camera, Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    //显示弹窗
    public static void showPopupWindow(int parentRes, List list, AppCompatActivity activity, int photoNum) {

        View parentView = LayoutInflater.from(activity).inflate(parentRes, null);
        // 一个自定义的布局，作为显示的内容
        final View contentView = LayoutInflater.from(activity).inflate(
                R.layout.photo_popwindow_layout, null);

        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        //设置弹窗的项目点击事件
        setPopupMenuItem(contentView, list, activity, popupWindow,photoNum);
        popupWindow.setTouchable(true);
        // view添加OnTouchListener监听判断获取触屏位置如果在布局外面则销毁弹出框
        contentView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // getTop View自身的顶边到其父布局顶边的距离,因为是根目录所以为0
                int height = contentView.findViewById(R.id.popup_window_layout).getTop();
                // getY 点击事件距离控件顶边的举例
                int y = (int) event.getY();
                // 当抬起 并且 y>height时（也就是 只要不点击ListView范围内）,dismiss popupWindow
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y > height) {
                        popupWindow.dismiss();
                    }
                }
                return true;
            }
        });

        // 设置SelectPicPopupWindow弹出窗体的背景
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框

        // 设置好参数之后再show
        // popupWindow.showAsDropDown(view);
        popupWindow.showAtLocation(parentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    //设置弹窗的项目点击事件
    private static void setPopupMenuItem(View view, final List list, final AppCompatActivity activity, final PopupWindow popupWindow
            , final int photoNum) {
        Button photoBut = (Button) view.findViewById(R.id.send_buy_take_photo);
        Button ablumBut = (Button) view.findViewById(R.id.send_buy_open_ablum);
        Button cancelBut = (Button) view.findViewById(R.id.send_buy_cancel);
        //设置拍照片，打开相机

        photoBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //照相
                takePicture(activity);
                //取消弹窗
                popupWindow.dismiss();

            }
        });
        //设置获取本地相册
        ablumBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAlbum(activity, list,photoNum);
                //取消弹窗
                popupWindow.dismiss();
            }
        });
        cancelBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //取消弹窗
                popupWindow.dismiss();
            }
        });
    }

    public static void openAlbum(AppCompatActivity activity, List list, int photoNum) {
        //打开本地相册
        PhotoPickerIntent intent = new PhotoPickerIntent(activity);

        intent.setSelectModel(SelectModel.MULTI);
        // intent.setShowCarema(true); // 是否显示拍照， 默认false
        intent.setMaxTotal(photoNum); // 最多选择照片数量，默认为4
        intent.setSelectedPaths((ArrayList<String>) list); // 已选中的照片地址， 用于回显选中状态
        activity.startActivityForResult(intent, REQUEST_CAMERA_CODE);
    }



    //打开摄像头
    public static void takePicture(FragmentActivity activity) {
        try {
            if (captureManager == null) {
                captureManager = new ImageCaptureManager(activity);
            }

            Intent intent = captureManager.dispatchTakePictureIntent(activity);

            activity.startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            Toast.makeText(activity, R.string.msg_no_camera, Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    //初始化默认照片
//    public static String inintBitmap(AppCompatActivity activity) {
//        Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.add_photo);
//
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//
//        return FileUtils.saveBitmap(bitmap, "add_photo");
//    }


    /**
     * 获取GridView Item宽度
     * @return
     */
    public static int getItemImageWidth(Context context){
        int cols = getNumColnums(context);
        int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        int columnSpace = context.getResources().getDimensionPixelOffset(com.lidong.photopicker.R.dimen.space_size);
        return (screenWidth - columnSpace * (cols-1)) / cols;
    }

    /**
     * 根据屏幕宽度与密度计算GridView显示的列数， 最少为四列列
     * @return
     */
    public static int getNumColnums(Context context){
        int cols = context.getResources().getDisplayMetrics().widthPixels / context.getResources().getDisplayMetrics().densityDpi;
        return cols < 4 ? 4 : cols;
    }


    /**
     * 裁剪原始的图片
     */
    private static final int CODE_RESULT_REQUEST = 4;

    private static final int REQUEST_CAMERA_CODE = 2;
    public static void cropRawPhoto(BaseActivity activity, Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        // 设置裁剪
        intent.putExtra("crop", "true");

        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, CODE_RESULT_REQUEST);
    }



}